package com.woyou.ui.activity;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Background;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.ViewById;

import com.citaq.ideliver.R;
import com.woyou.bean.Result;
import com.woyou.bean.UserInfo;
import com.woyou.bean.rpc.FeedBackReq;
import com.woyou.bean.rpc.FeedBackRes;
import com.woyou.service.NetWorkCenter;
import com.woyou.ui.api.IBackEventStrategy;
import com.woyou.ui.component.EditDialog;
import com.woyou.ui.component.EditDialog.BtnListener;
import com.woyou.utils.Dialog;

import android.annotation.SuppressLint;
import android.app.ActionBar.LayoutParams;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import retrofit.RetrofitError;

/**
 * 整个店铺的Activity
 * 
 */
@EActivity(R.layout.fm_serviceproblem)
public class ServiceProblemActivity extends BaseActivity implements IBackEventStrategy {

	private static final String IMAGE_UNSPECIFIED = "image/*";
	private static final int PHOTO_GRAPH = 1;// 拍照
	private static final int PHOTO_ZOOM = 2; // 缩放
	private static final int PHOTO_RESOULT = 3;// 结果
	Dialog dialog = new Dialog();
	EditDialog editDialog = new EditDialog();

	@ViewById
	// 头部标题，提交问题
	TextView head_title;
	@ViewById
	// 退出
	RelativeLayout myback, everyonesaybtn;
	@ViewById
	// 隐藏键盘
	LinearLayout rl, id_gallery;
	@ViewById
	// 提交问题
	Button submitproblem;
	// 问题内容
	@ViewById
	EditText serviceproblemcontext;
	// 上传图片
	@ViewById
	ImageView feed_picbtn;

	LayoutInflater mInflater;

	UserInfo userInfo;

	private PopupWindow mPopupWindow;
	private View imageContent;

	List<Bitmap> bitmapList = new ArrayList<Bitmap>();
	List<String> pathList = new ArrayList<String>();

	@AfterViews
	public void init() {
		// 初始化数据
		initView();
		userInfo = mUserModel.getUserInfo();
		mInflater = LayoutInflater.from(this);
		picInitView();

		// 监听是否退出
		editDialog.setBtnListener(new BtnListener() {
			@Override
			public void pressBtn(int id, String str) {
				switch (id) {
				case R.id.ok_button:
					if (str.equals("serviceproblem_back")) {
						finish();
					}
					break;
				default:
					break;
				}
			}
		});
	}

	// 退出
	@Click({ R.id.myback, R.id.submitproblem, R.id.feed_picbtn, R.id.rl })
	void OnClick(View view) {
		switch (view.getId()) {
		case R.id.myback:
			// 退出服务问题界面
			hideSoftInput(this, serviceproblemcontext);
			if (!serviceproblemcontext.getText().toString().equals("")
					&& serviceproblemcontext.getText().toString().length() > 0) {
				editDialog.Dialog(mContext, serviceproblemcontext, R.id.serviceproblemcontext, "是否放弃输入？", "isDialog");
			} else {
				this.finish();
			}
			break;
		case R.id.submitproblem:
			// 提交服务问题反馈
			hideSoftInput(this, serviceproblemcontext);
			if (!serviceproblemcontext.getText().toString().equals("")
					&& serviceproblemcontext.getText().toString().length() > 0) {
				feedBack();
			} else {
				showToast("请先输入反馈内容");
			}
			break;
		case R.id.feed_picbtn:
			// 拍照
			showImageSelect();
			break;
		case R.id.rl:
			// 拍照
			hideSoftInput(this, serviceproblemcontext);
			break;
		default:
			break;
		}
	}

	public void initView() {
		head_title.setText("商户问题");
		initImageSelect();
	}

	// 是指意见反馈的请求参数
	public void feedBack() {
		try {
			FeedBackReq feedback = new FeedBackReq();
			if (userInfo.getuId() != null && userInfo.getuId().length() > 0) {
				feedback.setuId(userInfo.getuId());
				feedback.setPwd(userInfo.getPwd());
			} else {
				feedback.setuId("woyouxinxi");
				feedback.setPwd("");
			}
			feedback.setFeedback(serviceproblemcontext.getText().toString());
			feedback.setType(1);
			feedBackResult(feedback);
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

	@Background
	void feedBackResult(FeedBackReq feedBackReq) {
		if (!NetWorkCenter.isNetworkConnected(this)) {
			showToastOnUI("请检查你的网络!");
			return;
		}
		showProgressDialog();
		try {
			Result<FeedBackRes> result = mUserModel.v2_1feedback(feedBackReq);
			if (result != null && result.code == 1) {
				FeedBackRes feedBackRes = result.getData();
				if (pathList != null && pathList.size() > 0) {
					// 上传头像
					showToastOnUI(result.getMsg());
					this.finish();
				} else {
					showToastOnUI(result.getMsg());
					this.finish();
				}
			} else if (result != null && result.code == -3) {
				dialog.LoginToast(mContext, result.msg);
			} else {
				showToastOnUI(result.msg);
			}
			dismissProgressDialog();
		} catch (RetrofitError e) {
			dismissProgressDialog();
			switch (e.getKind()) {
			case HTTP:
				showToastOnUI("很遗憾，网路不给力！");
				return;
			case CONVERSION:
				showToastOnUI("很抱歉，服务器又任性了！");
				return;
			case NETWORK:
				showToastOnUI("很遗憾，网路不给力！");
				return;
			case UNEXPECTED:
				showToastOnUI("很抱歉，服务器又任性了！");
				return;
			}
		}
	}

	Intent intent;

	@SuppressLint("NewApi")
	private void initImageSelect() {
		imageContent = View.inflate(this, R.layout.get_image, null);
		// 拍照
		imageContent.findViewById(R.id.take_photo).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
				intent.putExtra(MediaStore.EXTRA_OUTPUT,
						Uri.fromFile(new File(Environment.getExternalStorageDirectory(), "temp.jpg")));
				startActivityForResult(intent, PHOTO_GRAPH);
				if (mPopupWindow != null && mPopupWindow.isShowing()) {
					mPopupWindow.dismiss();
				}
			}
		});
		// 相册选择
		imageContent.findViewById(R.id.upload).setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				intent = new Intent(Intent.ACTION_PICK, null);
				intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, IMAGE_UNSPECIFIED);
				startActivityForResult(intent, PHOTO_ZOOM);
				if (mPopupWindow != null && mPopupWindow.isShowing()) {
					mPopupWindow.dismiss();
				}
			}
		});
		// 取消
		imageContent.findViewById(R.id.cancel).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				mPopupWindow.dismiss();
			}
		});
		// 取消
		imageContent.findViewById(R.id.get_imagelayout).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				mPopupWindow.dismiss();
			}
		});
	}

	/**
	 * show出选项卡 tanglc
	 */
	private void showImageSelect() {
		if (mPopupWindow != null && mPopupWindow.isShowing()) {
			mPopupWindow.dismiss();
		}
		mPopupWindow = new PopupWindow(imageContent, LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
		mPopupWindow.setFocusable(true);
		mPopupWindow.showAtLocation(rl, Gravity.BOTTOM, 0, 0);
	}

	String path = null;

	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		// 拍照
		if (requestCode == PHOTO_GRAPH && resultCode == -1) {
			// 设置文件保存路径
			File picture = new File(Environment.getExternalStorageDirectory() + "/temp.jpg");
			path = picture.getPath();
			startPhotoZoom(Uri.fromFile(picture));
		}
		// 读取相册缩放图片
		if (requestCode == PHOTO_ZOOM && data != null) {
			Uri originalUri = data.getData(); // 获得图片的uri
			String[] proj = { MediaStore.Images.Media.DATA };
			// 好像是android多媒体数据库的封装接口，具体的看Android文档
			@SuppressWarnings("deprecation")
			Cursor cursor = this.managedQuery(originalUri, proj, null, null, null);
			// 按我个人理解 这个是获得用户选择的图片的索引值
			int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
			// 将光标移至开头 ，这个很重要，不小心很容易引起越界
			cursor.moveToFirst();
			// 最后根据索引值获取图片路径
			path = cursor.getString(column_index);
			startPhotoZoom(data.getData());
		}
		// 处理结果
		if (requestCode == PHOTO_RESOULT && data != null) {
			Bundle extras = data.getExtras();
			if (extras != null) {
				Bitmap photo = extras.getParcelable("data");
				try {
					saveImage(photo, path);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	};

	/**
	 * 收缩图片
	 * 
	 * @param uri
	 */
	public void startPhotoZoom(Uri uri) {
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(uri, IMAGE_UNSPECIFIED);
		intent.putExtra("crop", "true");
		// aspectX aspectY 是宽高的比例
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		// outputX outputY 是裁剪图片宽高
		intent.putExtra("outputX", 300);
		intent.putExtra("outputY", 300);
		intent.putExtra("return-data", true);
		startActivityForResult(intent, PHOTO_RESOULT);
	}

	/**
	 * 保存头像 tanglc
	 * 
	 * @param bmp
	 * @throws IOException
	 */
	private void saveImage(Bitmap bmp, final String path) throws IOException {
		File fImage = new File(Environment.getExternalStorageDirectory(), "testPng");
		fImage.createNewFile();
		FileOutputStream iStream = new FileOutputStream(fImage);
		bmp.compress(CompressFormat.PNG, 100, iStream);
		iStream.close();

		bitmapList.add(bmp);
		pathList.add(path);
		picInitView();
	}

	private void picInitView() {
		if (bitmapList != null && bitmapList.size() > 0) {
			if (bitmapList.size() > 3) {
				feed_picbtn.setVisibility(View.GONE);
			} else {
				feed_picbtn.setVisibility(View.VISIBLE);
			}
			id_gallery.removeAllViews();
			for (int i = 0; i < bitmapList.size(); i++) {
				View view = mInflater.inflate(R.layout.item_gallery, id_gallery, false);
				ImageView img = (ImageView) view.findViewById(R.id.id_index_gallery_item_image);
				ImageButton imgbtn = (ImageButton) view.findViewById(R.id.deletepic);
				imgbtn.setTag(i);
				imgbtn.setOnClickListener(new View.OnClickListener() {

					@Override
					public void onClick(View v) {
						int no = (Integer) v.getTag();
						bitmapList.remove(no);
						picInitView();
					}
				});
				img.setImageBitmap(bitmapList.get(i));
				id_gallery.addView(view);
			}
		} else {
			id_gallery.removeAllViews();
		}
	}

	/**
	 * 隐藏输入法
	 * 
	 * @param context
	 * @param achor
	 */
	public void hideSoftInput(Context context, View achor) {
		InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(achor.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
	}

	@Override
	public boolean backOperate() {

		return true;
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
			if (!serviceproblemcontext.getText().toString().equals("")
					&& serviceproblemcontext.getText().toString().length() > 0) {
				editDialog.Dialog(mContext, serviceproblemcontext, R.id.serviceproblemcontext, "是否放弃输入？", "isDialog");
			} else {
				this.finish();
			}
		}
		return true;
	}

}
